import { getData } from '@vimi/utils-api'
import { SERVICE_NAME } from '@/gov/plugins/constant'

const state = {
  accessData: {},
  accessIndustryData: {},
}

const getters = {
  accessData: state => state.accessData,
  accessIndustryData: state => state.accessIndustryData,
}

const actions = {
  async getAccessData({ commit, rootGetters }, force = false) {
    if (!force && state.accessData.credit_agency_access_id) {
      return Promise.resolve(state.accessData)
    }
    const params = {
      access_agency_id: rootGetters.clientId,
      'bus_type.eq': 2,
    }
    const res = await getData(SERVICE_NAME, 'credit_agency_access', params, { create_time: 'desc' })
    const data = (res && res.data && res.data.length && res.data[0]) || {}
    commit('accessData', data)
    return data
  },

  async getAccessIndustryData({ commit, rootGetters }, force = false) {
    if (!force && state.accessIndustryData.credit_agency_access_id) {
      return Promise.resolve(state.accessIndustryData)
    }
    const params = {
      access_agency_id: rootGetters.clientId,
      'bus_type.eq': 4,
    }
    const res = await getData(SERVICE_NAME, 'credit_agency_access', params, { create_time: 'desc' })
    const data = (res && res.data && res.data.length && res.data[0]) || {}
    commit('accessIndustryData', data)
    return data
  },
}

const mutations = {
  accessData: (state, payload) => (state.accessData = payload),
  accessIndustryData: (state, payload) => (state.accessIndustryData = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
